<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/11/8
 * Time: 3:22 PM
 */

namespace App\Library\User;


use App\Models\Trees;
use App\Models\User;
use App\Models\UserTree;

class TreeManager
{
    public function __construct()
    {
    }

    public static function buyTree(User $user, $treeid, $quantity=1)
    {
        $tree = Trees::find($treeid);
        if ($tree)
        {
            $energy = $tree->bubbles/ ($tree->days * 24);
            $wallet = $user->wallet()->firstOrCreate([]);

            for ($i=0; $i<$quantity; $i++)
            {
                if ($wallet->bonus_points >= $tree->points)
                {
                    $user->trees()->create([
                        'treeid'=>$treeid,
                        'bubbles'=>$tree->bubbles,
                        'days'=>$tree->days,
                        'energy'=>$energy
                    ]);
                    PointManager::takeOffPoints($user, $tree->points, 'buytree', '购买'.$quantity.'棵'.$tree->title, 0);
                }
            }
        }
    }

    public static function releaseBubbles()
    {
        $time = strtotime('-1 hours');
        UserTree::with('user')->where('released_at', '<', $time)->get()
            ->map(function (UserTree $tree){
                //气泡不足，删除茶树
                if ($tree->bubbles_released + $tree->energy > $tree->bubbles)
                {
                    $tree->delete();
                } else {
                    $tree->user->bubbles()->create([
                        'points'=>$tree->energy,
                        'treeid'=>$tree->id
                    ]);
                    $tree->released_at = time();
                    $tree->bubbles_released+= $tree->energy;
                    $tree->save();
                }
            });
    }
}
